<template>
  <el-scrollbar ref="scrollContainer" :vertical="false" class="scroll-container"
                @wheel.native.prevent="myHandleScroll">
    <slot/>
  </el-scrollbar>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';

@Component({
  components: {}
})
export default class ScrollPane extends Vue {
  private tagAndTagSpacing = 4;// tagAndTagSpacing
  @Ref('scrollContainer') private scrollContainer: any;

  scrollWrapper(): any {
    return this.scrollContainer.$refs.wrap;
  }

  myHandleScroll(e: any) {
    const eventDelta = e.wheelDelta || -e.deltaY * 40;
    this.scrollWrapper().scrollLeft += eventDelta / 4;
  }


  moveToTarget(currentTag: any) {
    const $container = (this as any).$refs.scrollContainer.$el;
    const $containerWidth = $container.offsetWidth;
    const $scrollWrapper: any = this.scrollWrapper();
    const tagList = (this as any).$parent.$refs.tag;

    let firstTag = null;
    let lastTag = null;

    // find first tag and last tag
    if (tagList.length > 0) {
      firstTag = tagList[0];
      lastTag = tagList[tagList.length - 1];
    }

    if (firstTag === currentTag) {
      $scrollWrapper.scrollLeft = 0;
    } else if (lastTag === currentTag) {
      $scrollWrapper.scrollLeft = $scrollWrapper.scrollWidth - $containerWidth;
    } else {
      // find preTag and nextTag
      const currentIndex = tagList.findIndex((item: any) => item === currentTag);
      const prevTag = tagList[currentIndex - 1];
      const nextTag = tagList[currentIndex + 1];

      // the tag's offsetLeft after of nextTag
      const afterNextTagOffsetLeft = nextTag.$el.offsetLeft + nextTag.$el.offsetWidth + this.tagAndTagSpacing;

      // the tag's offsetLeft before of prevTag
      const beforePrevTagOffsetLeft = prevTag.$el.offsetLeft - this.tagAndTagSpacing;

      if (afterNextTagOffsetLeft > $scrollWrapper.scrollLeft + $containerWidth) {
        $scrollWrapper.scrollLeft = afterNextTagOffsetLeft - $containerWidth;
      } else if (beforePrevTagOffsetLeft < $scrollWrapper.scrollLeft) {
        $scrollWrapper.scrollLeft = beforePrevTagOffsetLeft;
      }
    }
  }

  mounted() {
    this.scrollWrapper();
  }
}
</script>

<style scoped lang="scss">
.scroll-container {
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;

  ::v-deep(.el-scrollbar__bar) {
    bottom: 0;
  }

  ::v-deep(.el-scrollbar__view) {
    display: inline-block;
  }
}
</style>

